package com.mgr.controller;

import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.mgr.model.Transactions;
import com.mgr.service.AccountService;
import com.mgr.service.OTPService;
import com.mgr.service.SmsService;

@Controller
public class ExternalTransferController2 {

	@Autowired
	private SmsService smsService;

	@Autowired
	private OTPService otpService;

	@Autowired
	private AccountService accountService;

	private ResourceBundle rb = ResourceBundle
			.getBundle("com.mgr.messages.errorMessage");

	@RequestMapping("/externalTransfer2")
	public ModelAndView processexternalTransfer2(HttpSession session) {
		ModelAndView modeView = new ModelAndView();
		String id = (String) session.getAttribute("user");
		if (id == null || id == "") {
			modeView.setViewName("login");
		} else if (session.getAttribute("trans") != null
				&& session.getAttribute("balance") != null) {
			modeView.addObject(session.getAttribute("balance"));
			modeView.addObject("trans", session.getAttribute("trans"));
			modeView.setViewName("externalTransfer2.tile");
		} else {
			modeView.setViewName("redirect:externalTransfer1");
		}
		return modeView;
	}

	@RequestMapping("/ExternalTrans2")
	public ModelAndView doAction2(HttpSession session,HttpServletRequest request) {
		ModelAndView modeView = new ModelAndView();
		String id = (String) session.getAttribute("user");
		if (id == null || id == "") {
			modeView.setViewName("login");
		} else {
			Transactions trans = (Transactions) session.getAttribute("trans");
			if (trans == null || session.getAttribute("step1") == null) {
				modeView.setViewName("redirect:externalTransfer1");
			} else {
				Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
				modeView.addObject("trans", session.getAttribute("trans"));
				String answer = request.getParameter("answer");
				if (captcha.isCorrect(answer)) {
					String codeOTP = smsService.createOTP();
					session.setAttribute("codeOTP", codeOTP);
					int custId = Integer.parseInt((String) session.getAttribute("user"));
					if (otpService.sendEmail(custId, codeOTP)) {
						session.setAttribute("step2", true);
						modeView.setViewName("externalTransfer3.tile");
					} else {
						modeView.addObject("err", rb.getString("sentOTPWrong"));
						modeView.setViewName("externalTransfer2.tile");
					}
				} else {
					modeView.setViewName("externalTransfer2.tile");
					modeView.addObject("err", rb.getString("captchaWrong"));
				}
			}
		}
		return modeView;
	}
}
